﻿using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml.Serialization;

namespace CommonTool
{
    public class ConfigReader
    {
        /// <summary>
        /// 从Xml 获取对象
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="filePath"></param>
        /// <returns></returns>
        public static T ReadFromXml<T>(string filePath, Encoding encoding = null)
        {
            using (var reader = new StringReader(GetFileContent(filePath, encoding ?? Encoding.UTF8)))
            {
                return (T)new XmlSerializer(typeof(T)).Deserialize(reader);
               
            }
        }
        public static T ReadFromXml<T>(Type type,string filePath, Encoding encoding = null)
        {
            using (var reader = new StringReader(GetFileContent(filePath, encoding ?? Encoding.UTF8)))
            {
                return (T)new XmlSerializer(type).Deserialize(reader);

            }
        }
        /// <summary>
        /// 从 json 获取对象
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="filePath"></param>
        /// <returns></returns>
        public static T ReadFromJson<T>(string filePath,Encoding encoding =null)
        {
            using (var reader = new StringReader(GetFileContent(filePath, encoding??Encoding.UTF8)))
            {
                return JsonConvert.DeserializeObject<T>(reader.ReadToEnd());
            }
        }
        public static T ReadFromJson<T>(Type type,string filePath, Encoding encoding = null)
        {
            using (var reader = new StringReader(GetFileContent(filePath, encoding ?? Encoding.UTF8)))
            {
                return (T)JsonConvert.DeserializeObject(reader.ReadToEnd(), type);
            }
        }

        /// <summary>
        /// 获取文件内容
        /// </summary>
        /// <param name="path"></param>
        /// <returns></returns>
        private static string GetFileContent(string path, Encoding encoding)
        {
            return File.ReadAllText(path, encoding);
        }
    }
}
